package com.company.common.api.wrap.handler;

import java.util.concurrent.TimeUnit;

import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.common.api.wrap.config.ApiWrapProperties;
import com.company.common.api.wrap.store.WrapStore;

import cn.hutool.core.util.StrUtil;

public class WrapHandlerServer implements WrapHandler {

	private WrapStore wrapStoreApi;
	private Long legalTime = 300L;
	private String defaultSecret;

	public WrapHandlerServer(ApiWrapProperties apiWrapProperties, WrapStore wrapStoreApi) {

		if (apiWrapProperties != null) {
			this.legalTime = apiWrapProperties.getLegalTime() == null ? 300 : apiWrapProperties.getLegalTime();
			this.defaultSecret = apiWrapProperties.getSecret();
		}
		this.wrapStoreApi = wrapStoreApi;
	}

	public String getAppSecret(String appSecret) {
		if (StrUtil.isEmpty(appSecret)) {
			return defaultSecret;
		}
		return appSecret;
	}
	
	

	@Override
	public String getSignature(String appSecret, Object request) {
		return null;
	}

	@Override
	public void isLegalTime(long timestamp) {
		long diff = TimeUnit.MILLISECONDS.toSeconds(timestamp - System.currentTimeMillis());
		if (Math.abs(diff) > legalTime) {
			throw new BusinessException(BaseReturnEnum.NOT_AUTHC);
		}
	}

	@Override
	public void isReplayAttack(String appSecret, long timestamp, String nonce, String signature) {
		String sign=wrapStoreApi.getSign(appSecret, timestamp, nonce);
		if (signature.equals(sign)) {
			throw new BusinessException(BaseReturnEnum.NOT_AUTHC);
        } else {
        	wrapStoreApi.putSign(appSecret, timestamp, nonce, signature, legalTime);
        }
	}
	
	
	

}
